import 'package:f_base_one/components/OrderDetail.dart';
import 'package:f_base_one/components/ProductList.dart';
import 'package:f_base_one/model/Product.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      // home: const MyHomePage(title: '案例-商品订单'),
      routes: {
        '/': (context) => const MyHomePage(title: '案例-商品订单'),
        '/orderdetail': (context) => const Orderdetail(),
      },
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Product> _products = [];
  Map<int, bool> _selectedProducts = {};
  int _totalQuantity = 0;
  double _totalPrice = 0.0;

  @override
  void initState() {
    super.initState();
    _fetchProducts();
  }

  Future<void> _fetchProducts() async {
    // 模拟接口请求
    await Future.delayed(const Duration(seconds: 2));
    setState(() {
      _products = [
        Product(
          id: 1,
          createTime: "2024-08-15 21:49:48",
          orderState: "待发货",
          image:
              "https://yanxuan-item.nosdn.127.net/a09de222ed32efa8ffe359b1d5780574.jpg",
          name: "茶水分离杯耐热隔热玻璃杯茶水分离杯耐热隔热玻璃杯",
          totalNum: 2,
          curPrice: 119.5,
          attrsText: "规格: 白色240ml",
        ),
        Product(
          id: 2,
          createTime: "2024-08-16 10:30:00",
          orderState: "已发货",
          image:
              "https://yanxuan-item.nosdn.127.net/a09de222ed32efa8ffe359b1d5780574.jpg",
          name: "便携式保温杯",
          totalNum: 1,
          curPrice: 99.99,
          attrsText: "规格: 黑色500ml",
        ),
      ];
    });
  }

  void _toggleProductSelection(int productId, bool selected) {
    setState(() {
      _selectedProducts[productId] = selected;
      _calculateTotal();
    });
  }

  void _updateProductQuantity(int productId, int quantity) {
    setState(() {
      final productIndex = _products.indexWhere(
        (product) => product.id == productId,
      );
      if (productIndex != -1) {
        _products[productIndex] = _products[productIndex].copyWith(
          totalNum: quantity,
        );
        _calculateTotal();
      }
    });
  }

  void _calculateTotal() {
    int totalQuantity = 0;
    double totalPrice = 0.0;

    for (var product in _products) {
      if (_selectedProducts[product.id] == true) {
        totalQuantity += product.totalNum;
        totalPrice += product.curPrice * product.totalNum;
      }
    }

    setState(() {
      _totalQuantity = totalQuantity;
      _totalPrice = totalPrice;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Stack(
        alignment: Alignment.bottomRight,
        fit: StackFit.expand,
        children: [
          SingleChildScrollView(
            padding: const EdgeInsets.all(12),
            child: Column(
              children: <Widget>[
                FutureBuilder<List<Product>>(
                  future: Future.value(_products),
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.waiting) {
                      return const Center(child: CircularProgressIndicator());
                    } else if (snapshot.hasError) {
                      return Center(child: Text('Error: ${snapshot.error}'));
                    } else if (!snapshot.hasData || snapshot.data!.isEmpty) {
                      return const Center(child: Text('No products found.'));
                    } else {
                      return ProductList(
                        products: snapshot.data!,
                        selectedProducts: _selectedProducts,
                        onProductSelected: _toggleProductSelection,
                        onUpdateProductQuantity: _updateProductQuantity,
                      );
                    }
                  },
                ),
              ],
            ),
          ),
          Positioned(
            bottom: 16,
            right: 16,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.end,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Row(
                  children: [
                    Text('共$_totalQuantity件商品'),
                    const SizedBox(width: 10),
                    Text('合计：￥ $_totalPrice'),
                  ],
                ),
                const SizedBox(height: 10),
                ElevatedButton(
                  onPressed: () {
                    setState(() {
                      _selectedProducts.clear();
                      _totalQuantity = 0;
                      _totalPrice = 0.0;
                    });
                  },
                  child: const Text('立即支付'),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
